package br.com.mundodaprata.store.model;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.PostPersist;
import javax.persistence.Table;
import javax.persistence.Transient;

@Entity
@Table(name="order_item")
public class OrderItem extends AbstractEntity {
   
   private static final long serialVersionUID = 1L;
   
   @Id
   @GeneratedValue(strategy=GenerationType.IDENTITY)
   @Column
   private Long              code;
   
   @ManyToOne
   @JoinColumn(name="order_number")
   private Order             order;
   
   @ManyToOne
   @JoinColumn(name="product")
   private Product           product;
   
   @Column
   private Integer           quantity;
   
   @Column
   private Double            discount;
   
   @Column
   private Double            price;
   
   @Transient
   private Double            finalPrice;
   
   {
      quantity = 1;
      discount = 0.0;
   }
   
   public Long getCode() {
      return code;
   }
   
   public void setCode(Long code) {
      this.code = code;
   }
   
   public Order getOrder() {
      return order;
   }
   
   public void setOrder(Order order) {
      this.order = order;
   }
   
   public Product getProduct() {
      return product;
   }
   
   public void setProduct(Product product) {
      this.product = product;
      
      setPrice(product.getPrice());
   }
   
   public Integer getQuantity() {
      return quantity;
   }
   
   public void setQuantity(Integer quantity) {
      this.quantity = quantity;
      
      updatePrice();
   }
   
   public Double getDiscount() {
      return discount;
   }
   
   public void setDiscount(Double discount) {
      this.discount = discount;
      
      updatePrice();
   }
   
   public Double getPrice() {
      return price;
   }
   
   public void setPrice(Double price) {
      this.price = price;
      
      updatePrice();
   }
   
   public void updatePrice(){
      double price = getQuantity() * getPrice();
      price -= price * (getDiscount() / 100);
      
      this.finalPrice = price;
   }
   
   public Double getFinalPrice() {
      return finalPrice;
   }
   
   @PostPersist
   public void decrease(){
	   getProduct().updateStock(-getQuantity());
   }
}